package com.loan.web.api;

import com.loan.entity.Application;
import com.loan.entity.ResponseResult;
import com.loan.group.ApplicationAddGroup;
import com.loan.service.ApplicationService;
import com.loan.util.Audience;
import com.loan.util.JwtUtil;
import com.loan.vo.ApplyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: wYin
 * @Date: 2022/1/17 22:41
 */
@RestController
@RequestMapping("/api/app")
@Slf4j
public class ApplicationController {
    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private Audience audience;

    /**
     * 添加申请表信息:接受JSON数据
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<Void> addAppliInfo(
            @RequestBody Application application
            /*@RequestHeader String token*/){
        log.info("添加申请信息");
        log.info("参数:{}",application);
        //设置申请表状态为提交
        application.setStatus(Application.APPLY);

        //TODO:从jwt中获取提交申请的员工id
        int empId = 1/*JwtUtil.parseJwtForId(token, audience)*/;
        //执行添加
        boolean flag = applicationService.insert(application,empId);
        if(flag){
            return ResponseResult.SUCCESS;
        }
        return ResponseResult.FAIL;
    }

    @RequestMapping("/list")
    public ResponseResult<List<Application>> list(){
        List<Application> list = applicationService.list();
        return new ResponseResult<>(list);
    }

    /**
     * 条件查询
     * @param application
     * @return
     */
    @RequestMapping("/condition")
    public ResponseResult<List<Application>> condition(@RequestBody Application application){

        log.info("\n-------------------条件查询--------------------------" +
                "\n参数:{}",application);

        List<Application> applications = applicationService.findByCondition(application);
        return new ResponseResult<>(applications);
    }

    /**
     * 审核
     * @param applyVO
     * @return
     */
    @RequestMapping("/examine")
    public ResponseResult<Void> examine(@RequestBody ApplyVO applyVO){

        log.info("\n----------------------申请审核-----------------------\n参数:{}",applyVO);

        //TODO:从jwt中解析empId
        applyVO.setEmpId(1);
        applicationService.examine(applyVO);
        return ResponseResult.SUCCESS;
    }



    /**
     * 处理校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Void> exceptionHandler(MethodArgumentNotValidException ex){
        /*
         * 返回统一响应码：500
         */
        return new ResponseResult<>(500,ex.getMessage());
    }
}
